from django.core.cache import cache
from django.http import JsonResponse

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):

    def get(self, request):
        # 查询所有省份
        province_list = cache.get('provinces')
        if province_list is None:
            try:
                provinces = Area.objects.filter(parent=None)
                # 转换为字典
                province_list = []
                for province in provinces:
                    province_list.append({"id": province.id, "name": province.name})

                    cache.set("provinces", province_list, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})

        # 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})

class SubAreaView(View):

    def get(self, request, id):

        sub_data = cache.get('sub_areas%s' % id)
        if sub_data is None:
            try:
                # 获取id 根据id查询省或者市的对象
                parent_obj = Area.objects.get(id=id)
                # 获取省或者市下一级的所有数据
                sub_objs = parent_obj.subs.all()
                # 转为字典
                subs = []
                for sub in sub_objs:
                    subs.append({"id": sub.id, "name": sub.name})

                sub_data = {"id": id, "name": parent_obj.name, "subs": subs}

                cache.set("sub_areas%s" % id, sub_data, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})

        # 返回数据
        return JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
